package cn.jasonone.views;

import cn.jasonone.model.PdfContent;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.Data;
import org.springframework.web.servlet.view.AbstractUrlBasedView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * PDF视图处理器
 * @author xujie
 * @version 1.0.0
 */
@Data
public class PdfView extends AbstractUrlBasedView {

    private final PdfContent pdfContent;

    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pdfContent.getTitle(),"UTF-8") + ".pdf");
        Document document = new Document(PageSize.A4);
        PdfWriter pdfWriter = PdfWriter.getInstance(document,response.getOutputStream());
        document.open();
        document.addAuthor(this.pdfContent.getAuthor());
        document.addCreator(pdfContent.getCreator() == null ||pdfContent.getCreator().isEmpty() ? pdfContent.getAuthor() : pdfContent.getCreator());
        document.addSubject(pdfContent.getSubject());
        document.addCreationDate();
        document.addTitle(pdfContent.getTitle());
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        InputStream inputStream=null;
        worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(pdfContent.getContent().getBytes("UTF-8")),inputStream, Charset.forName("UTF-8"),new CustomXMLWorkerFontProvider());
        document.close();
    }
}
